package com.boot.demo.config;

import com.boot.demo.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        LinkedHashMap<String,String> map=new LinkedHashMap<>();
        map.put("/login.html","anon");
        map.put("/login","anon");
        map.put("/logout","logout");
      /*  map.put("/userInfo.html","authc,roles[user],perms[see]");//roles[admin,user]是与的关系
        map.put("/userInfoAdd.html","authc,roles[admin],perms[add]");
        map.put("/userInfoDel.html","authc,roles[admin],perms[del]");*/
        map.put("/userInfo.html","authc,perms[see]");
        map.put("/userInfoAdd.html","authc,perms[admin:add]");
        map.put("/userInfoDel.html","authc,perms[admin:del]");
        map.put("/index.html","user");//认证或者记住我可以访问
        map.put("/**","authc");
        factoryBean.setLoginUrl("/login.html");
        factoryBean.setSuccessUrl("/index.html");
        //无权限
        factoryBean.setUnauthorizedUrl("/403.html");
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }
    @Bean
    public EhCacheManager ehCacheManager() {
        EhCacheManager em = new EhCacheManager();
        em.setCacheManagerConfigFile("classpath:ehcache.xml");
        return em;
    }
    @Bean
    public MyRealm myRealm() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(matcher);
        return myRealm;
    }
   /* @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
        daap.setProxyTargetClass(true);
        return daap;
    }*/
    @Bean
    public SecurityManager securityManager(EhCacheManager cacheManager){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm());
        securityManager.setCacheManager(cacheManager);
        return securityManager;
    }

}
